import axios from 'axios'
import store from '@/store'
import router from '@/router'

import request from '@/utils/request'

// 新axios实例
const instance = axios.create({
  baseURL: 'http://geek.itheima.net/',
  timeout: 5000
})
// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = store.state.user.token
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
  },
  err => Promise.reject(err)
)
// 响应拦截器
instance.interceptors.response.use(
  res => res,
  err => {
    if (err.response && err.response.status === 401) {
      // token失效
      store.commit('user/setToken', '')
      router.push(
        '/login?returnUrl=' + encodeURIComponent(router.currentRoute.fullPath)
      )
    }
    return Promise.reject(err)
  }
)
export default {
  name: 'HomePage',
  async created () {
    try {
      const res = await request({ url: 'v1_0/channels2' })
      console.log('成功', res.data)
    } catch (e) {
      console.log('失败', e.message)
    }
  }
}
